package zpf.zpf.controller;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import zpf.zpf.ZpfApplication;

import javax.servlet.http.HttpServletRequest;
import java.awt.datatransfer.StringSelection;
import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import java.util.*;

import java.awt.*;

import java.awt.event.*;

@RestController
@Slf4j
public class CsvContoller {


    public static HashMap<String ,User> map=new HashMap<>();

    @GetMapping("/queryEmail")
    public User queryEmail(@RequestParam(required = false) String email){
        User user=map.get(email);
        if(user==null){
            user=new User();
            user.setEmail("E-mails address not found, please ensure fill in the e-mail you signed up with.");
        }
        return user;
    }
    @GetMapping("/init")
    public Boolean ini(){
        try {
            map.clear();
            final CsvReader reader = CsvUtil.getReader();
            //假设csv文件在classpath目录下
            final List<User> result = reader.read(
                ResourceUtil.getUtf8Reader("/data/a.csv"), User.class);
            int i=0;
            for(User user:result){
                i++;
                user.setOther(user.getOther().replaceAll("\\n","<br/>"));
                if(map.get(user.getEmail())!=null){
                    log.error("邮箱已存在："+user.getEmail());
                }
                map.put(user.getEmail(),user);
                log.info("第"+i+"条数据"+user.getEmail());
            }
        } catch (final Exception e) {
            log.error("异常",e);
        }
        return Boolean.TRUE;
    }
    @GetMapping("/init2")
    public Boolean init2(){
        try {
            map.clear();

            ExcelReader reader = ExcelUtil.getReader("/data/a.xlsx");
            List<User> result = reader.readAll(User.class);
            int i=0;
            for(User user:result){
                i++;
                if(map.get(user.getEmail())!=null){
                    log.error("邮箱已存在："+user.getEmail());
                }
                if(user.getOther()!=null){
                    user.setOther(user.getOther().replaceAll("\\n","<br/>"));
                }
                map.put(user.getEmail(),user);
                log.info("第"+i+"条数据"+user.getEmail());
            }
        } catch (final Exception e) {
            log.error("异常",e);
        }
        return Boolean.TRUE;
    }
    @GetMapping("/forward")
    public String forward(){
        HttpServletRequest request =
            ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        log.info("--------header---------------");
        while (headerNames.hasMoreElements()) {
            String headName = (String)((Enumeration)headerNames).nextElement();
            log.info(headName + ":" + request.getHeader(headName));
            if(headName.toLowerCase().contains("x-forwarded-for")){
                return request.getHeader(headName);
            }
        }
        log.info("RemoteAddr:"+request.getRemoteAddr());
        log.info("RemoteHost:"+request.getRemoteHost());
        log.info("RemoteUser:"+request.getRemoteUser());
        log.info("RemotePort:"+request.getRemotePort());
        try {
            final List<String> jsonFile = FileUtils.readLines(new File("/data/a.csv"));
            for (final String str : jsonFile) {
                final String[] data = str.split(",");
                if (data.length == 2) {
                    User user=new User();
                    user.setEmail(data[0]);
                    user.setResult(data[1]);
                    map.put(user.getEmail(),user);
                }
            }
        } catch (final Exception e) {
            log.error("异常",e);
        }
        return "success";
    }

    @SneakyThrows
    @GetMapping("/keydown")
    public String keydown(){
        log.info("mac keydown");
        ZpfApplication.queue.put("mac keydown");
//        //声明一个StingSelection 对象，并使用String的参数完成实例化；
//        StringSelection stringSelection = new StringSelection("我是机器人-allSchool-推广文案..来自按键精灵的复制");
//        //使用Toolkit对象的setContents将字符串放到粘贴板中 ；
//       Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
//        Robot robot = null ;
//        try{
//            robot = new Robot();
//            robot.setAutoDelay(100);
//        }catch(AWTException e){
//            log.info("robot初始化错误:",e);
//            return "fail";
//        }
//        //按下command v键 ；
//        robot.keyPress(KeyEvent.VK_META);
//        robot.keyPress(KeyEvent.VK_V);
//        //command v 键
//        robot.keyRelease(KeyEvent.VK_V);
//        robot.keyRelease(KeyEvent.VK_META);
//        char c = "A".toLowerCase().charAt(0);
//        for(int i=0;i<3;i++){
//            //按键
//            robot.keyPress(c);
//            //释放
//
//            robot.keyRelease(c);
//
//            robot.setAutoDelay(500);
//        }
        return "success";
    }
    @SneakyThrows
    @GetMapping("/keydown_win")
    public String keydownWin(){
        log.info("win keydown");
        //声明一个StingSelection 对象，并使用String的参数完成实例化；
        StringSelection stringSelection = new StringSelection("我是机器人-allSchool-推广文案");
        //使用Toolkit对象的setContents将字符串放到粘贴板中 ；
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
        Robot robot = null ;
        try{
            robot = new Robot();
            robot.setAutoDelay(100);
        }catch(AWTException e){
            log.info("robot初始化错误:",e);
            return "fail";
        }
        //按下command v键 ；
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        //command v 键
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        return "success";
    }


}
